<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['invoice:invoice_products:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          v-hasPermi="['invoice:invoice_products:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['invoice:invoice_products:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['invoice:invoice_products:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="invoice_productsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="主键ID" width="90" align="center" prop="id" />
      <el-table-column label="商品名称" width="120" align="center" prop="productName" />
      <el-table-column
        label="规格型号"
        width="130"
        align="center"
        prop="specificationModel"
      />
      <el-table-column label="单位" width="140" align="center" prop="unit" />
      <el-table-column label="税率" width="140" align="center" prop="taxRate" >
        <template #default="scope">
          <span>{{ (scope.row.taxRate * 100).toFixed(0) }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="单价" width="100" align="center" prop="unitPrice" />
      <el-table-column
        label="税收分类码"
        width="140"
        align="center"
        prop="taxCategoryCode"
      />
      <el-table-column label="征税项目" width="200" align="center" prop="projectName" />
      <el-table-column label="计税方法" width="200" align="center" prop="methodName" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['invoice:invoice_products:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['invoice:invoice_products:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改开票商品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="invoice_productsRef"
        :model="form"
        :rules="rules"
        label-width="90px"
      >
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specificationModel">
          <el-input
            v-model="form.specificationModel"
            placeholder="请输入规格型号"
          />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="税率" prop="taxRate">
          <div style="display: flex; align-items: center">
            <el-input
              v-model="form.taxRate"
              placeholder="请输入税率"
              style="flex: 1"
            />
            <span style="margin-left: 5px">%</span>
          </div>
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input
            v-model="form.unitPrice"
            placeholder="请输入单价"
            type="number"
          />
        </el-form-item>
        <el-form-item label="税收分类码" prop="taxCategoryCode">
          <el-input
            v-model="form.taxCategoryCode"
            placeholder="请输入税收分类码"
          />
        </el-form-item>
        <el-form-item label="征税项目" prop="taxProjectId">
          <el-select v-model="form.taxProjectId" placeholder="请选择征税项目">
            <el-option v-for="item in projectList" :label="item.projectName" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="计税方法" prop="taxCalculationMethod">
          <el-select
            v-model="form.taxMethodId"
            placeholder="请选择计税方法"
          >
            <el-option v-for="item in methodList" :label="item.methodName" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Invoice_products">
import {
  listInvoice_products,
  getInvoice_products,
  delInvoice_products,
  addInvoice_products,
  updateInvoice_products,
  getTaxProjectsAll,
  getTaxMethodsAll,
} from "@/api/invoice/invoice_products";
import { ref } from "vue";

const { proxy } = getCurrentInstance();

const invoice_productsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    productName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" },
    ],
    unitPrice: [
      { required: true, message: "单价不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询开票商品列表 */
function getList() {
  loading.value = true;
  listInvoice_products(queryParams.value).then((response) => {
    invoice_productsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    productName: null,
    specificationModel: null,
    unit: null,
    taxRate: null,
    unitPrice: null,
    taxCategoryCode: null,
    taxProjectId: null,
    taxMethodId: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
  };
  proxy.resetForm("invoice_productsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加开票商品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getInvoice_products(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改开票商品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["invoice_productsRef"].validate((valid) => {
    if (valid) {
      // 处理税率，将百分比转换为小数
      if (form.value.taxRate) {
        form.value.taxRate = parseFloat(form.value.taxRate) / 100;
      }

      if (form.value.id != null) {
        updateInvoice_products(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInvoice_products(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除开票商品编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delInvoice_products(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "invoice/invoice_products/export",
    {
      ...queryParams.value,
    },
    `invoice_products_${new Date().getTime()}.xlsx`
  );
}

const projectList = ref([]);
const methodList = ref([]);

function getSelectData() {
  getTaxProjectsAll().then((response) => {
    projectList.value = response.data;
  });
  getTaxMethodsAll().then((response) => {
    methodList.value = response.data;
  });
}

getSelectData();
getList();
</script>
